package com.software.levelupandroid.home.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.recyclerview.widget.RecyclerView;

import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.home.ui.home.HomeViewModel;
import com.software.levelupandroid.home.ui.todayTask.TodayTaskViewModel;
import com.software.levelupandroid.taskCount.view.TaskCountActivity;
import com.software.levelupandroid.taskIssue.view.activity.TaskIssueActivity;
import com.software.levelupandroid.utils.DateUtil;
import com.software.levelupandroid.utils.MenuUtil;
import com.software.levelupandroid.utils.UserUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 任务Item的Adapter
 * @Author LiangYaJie
 * @CreateTime 2024年05月03日 20:14:56
 */
public class TaskItemAdapter extends RecyclerView.Adapter<TaskItemAdapter.ViewHolder> {

    private List<Task> taskList = new ArrayList<>();
    private Context context;
    private HomeViewModel homeViewModel;
    private TodayTaskViewModel todayTaskViewModel;
    private static final int TYPE_DONE = 1;
    private static final int TYPE_UNDONE = -1;
    private static final int TYPE_ONGOING = 0;

    @Override
    public int getItemViewType(int position) {
        int status = taskList.get(position).getStatus();
        if (status == 1){
            return TYPE_DONE;
        } else if (status == -1) {
            return TYPE_UNDONE;
        }else {
            return TYPE_ONGOING;
        }
    }

    public TaskItemAdapter(List<Task> taskList) {
        this.taskList = taskList;
    }

    public TaskItemAdapter(List<Task> taskList, Context context) {
        this.taskList = taskList;
        this.context = context;
    }

    public TaskItemAdapter(Context context, HomeViewModel viewModel) {
        this.context = context;
        this.homeViewModel = viewModel;
    }

    public TaskItemAdapter(Context context, TodayTaskViewModel viewModel) {
        this.context = context;
        this.todayTaskViewModel = viewModel;
    }

    @NonNull
    @Override
    public TaskItemAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = null;
        if (viewType == TYPE_DONE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_timeline_done, parent, false);
        }else if (viewType == TYPE_UNDONE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_timeline_undone, parent, false);
        }else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_timeline_ongoing, parent, false);
        }
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull TaskItemAdapter.ViewHolder holder, int position) {
        Task task = taskList.get(position);
        holder.tbFinish.setOnCheckedChangeListener(null);

        //设置任务完成状态
        holder.tbFinish.setChecked(task.getStatus() == 1);

        //设置任务标题
        holder.tvTaskTitle.setText(task.getTaskTitle());

        //设置开始时间
        String startTime = task.getStartTime();
        if (startTime != null){
            String[] start = startTime.split(" ");
            holder.tvTimeStart.setText(start[1]);
            //设置结束时间
            if (task.getEndTime() == null && task.getTaskType() != 2){
                holder.tvTimeEnd.setVisibility(View.INVISIBLE);
                holder.tvTo.setVisibility(View.INVISIBLE);
            }else {
                holder.tvTimeEnd.setVisibility(View.VISIBLE);
                holder.tvTo.setVisibility(View.VISIBLE);
                String endTime = task.getEndTime();
                String[] end = endTime.split(" ");
                if (start[0].equals(end[0]))
                    holder.tvTimeEnd.setText(end[1]);
                else
                    holder.tvTimeEnd.setText(endTime);
            }
        }

        //设置任务类型
        if (task.getTaskType() == 1){
            holder.tvTaskType.setText("通知型任务");
        } else if (task.getTaskType() == 2) {
            holder.tvTaskType.setText("计时型任务");
            if (task.getStatus() == 0){
                holder.tbFinish.setVisibility(View.INVISIBLE);
                holder.tvCount.setVisibility(View.VISIBLE);
            }else {
                holder.tbFinish.setVisibility(View.VISIBLE);
                holder.tvCount.setVisibility(View.INVISIBLE);
            }
        }else if (task.getTaskType() == 3){
            holder.tvTaskType.setText("系统任务");
        }

        //设置任务优先级
        switch (task.getPriority()){
            case 0:
                holder.tvPriority.setText("不重要不紧急");
                break;
            case 1:
                holder.tvPriority.setText("重要不紧急");
                break;
            case 2:
                holder.tvPriority.setText("不重要紧急");
                break;
            case 3:
                holder.tvPriority.setText("重要且紧急");
                break;
        }

        //恢复监听器
        holder.tbFinish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                User user = UserUtil.getUser(context);
                System.out.println(user);
                if (b){
                    task.setStatus(1);
                    user.setExperience(user.getExperience() + task.getExperience());
                    if (homeViewModel != null)
                        homeViewModel.updateExperience(user.getExperience(),context);
                    else
                        todayTaskViewModel.updateExperience(user.getExperience(), context);
                    UserUtil.saveUser(user, context);
                }else {
                    task.setStatus(0);
                    if (task.getStartTime() != null){
                        String start = task.getStartTime();
                        Long startLong = DateUtil.convertStringToLong(start, "yyyy年MM月dd日 HH:mm");
                        Long nowLong = DateUtil.getNowTimeLong();
                        if (startLong < nowLong){
                            task.setStatus(-1);
                        }else {
                            task.setStatus(0);
                        }
                    }
                    user.setExperience(user.getExperience() - task.getExperience());
                    if (homeViewModel != null)
                        homeViewModel.updateExperience(user.getExperience(),context);
                    else
                        todayTaskViewModel.updateExperience(user.getExperience(), context);
                    UserUtil.saveUser(user, context);
                }
                //更新任务状态到数据源
                if (homeViewModel != null){
                    if (task.getTaskType() != 0) homeViewModel.isFinishTask(task, context);
                    else homeViewModel.isFinishToDoTask(task, context);
                }

                if (todayTaskViewModel != null){
                    if (task.getTaskType() != 0) todayTaskViewModel.isFinishTask(task, context);
                    else homeViewModel.isFinishToDoTask(task, context);
                }
                notifyItemChanged(holder.getAdapterPosition());
            }
        });

        //设置计时型任务的计时按钮点击事件
        if (holder.tvCount != null && task.getTaskType() == 2){
            holder.tvCount.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, TaskCountActivity.class);
                    intent.putExtra("task", task);
                    context.startActivity(intent);
                }
            });
        }


        //设置菜单按钮的点击监听器
        holder.ibMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popup = new PopupMenu(view.getContext(), view);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.item_menu, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()){
                            case R.id.item_edit:
                                Intent intent = new Intent(context, TaskIssueActivity.class);
                                intent.putExtra("task", task);
                                intent.putExtra("flag", 1);
                                context.startActivity(intent);
                                return true;
                            case R.id.item_delete:
                                if (homeViewModel != null){
                                    if (task.getTaskType() != 0) homeViewModel.deleteTask(task, context);
                                    else homeViewModel.deleteToDoTask(task, context);
                                }
                                if (todayTaskViewModel != null){
                                   if (task.getTaskType() != 0) todayTaskViewModel.deleteTask(task, context);
                                   else homeViewModel.deleteToDoTask(task, context);
                                }
                                notifyDataSetChanged();
                                return true;
                            default:
                                return false;
                        }
                    }
                });
                popup.show();
            }
        });

        //设置每个item的点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, TaskIssueActivity.class);
                intent.putExtra("task", task);
                intent.putExtra("flag", 1);
                context.startActivity(intent);
            }
        });

    }

    @Override
    public int getItemCount() {
        return taskList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTaskTitle;
        private TextView tvTimeStart;
        private TextView tvTimeEnd;
        private TextView tvTaskType;
        private TextView tvPriority;
        private TextView tvTo;
        private ImageButton ibMore;
        private ToggleButton tbFinish;
        private TextView tvCount;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTaskTitle = itemView.findViewById(R.id.tv_taskTitle);
            tvTimeStart = itemView.findViewById(R.id.tv_timeStart);
            tvTimeEnd = itemView.findViewById(R.id.tv_timeEnd);
            tvTaskType = itemView.findViewById(R.id.tv_taskType);
            tvPriority = itemView.findViewById(R.id.tv_priority);
            tvTo = itemView.findViewById(R.id.tv_to);
            ibMore = itemView.findViewById(R.id.ib_more);
            tbFinish = itemView.findViewById(R.id.tb_finish);
            tvCount = itemView.findViewById(R.id.tv_count);
        }
    }

    /**
     * 更新任务列表
     * @param tasks
     */
    public void updateTaskList(List<Task> tasks){
        this.taskList.clear();
        this.taskList.addAll(tasks);
        notifyDataSetChanged();
    }

    /**
     * 任务列表新增
     * @param tasks
     */
    public void addTaskList(List<Task> tasks){
        this.taskList.addAll(tasks);
        notifyDataSetChanged();
    }

}
